package com.example.runningman.user;

import androidx.appcompat.app.AppCompatActivity;
import okhttp3.FormBody;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Toast;

import com.example.runningman.MainActivity;
import com.example.runningman.R;
import com.example.runningman.bean.User;
import com.example.runningman.run.DynamicDemo;
import com.example.runningman.util.SPUtil;
import com.google.gson.Gson;

import java.io.IOException;
import java.lang.ref.WeakReference;

public class LoginActivity extends AppCompatActivity implements View.OnClickListener {
    Button regs;
    EditText user_edit;
    EditText password_edit;
    Button login;
    private static Gson gson=new Gson();
    private Mhandler mHandler;

    final OkHttpClient client = new OkHttpClient();
    private class Mhandler extends Handler {
        private WeakReference<LoginActivity> mActivity;

        public Mhandler(LoginActivity activity){
            mActivity = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(msg.what==1){
                String ReturnMessage = (String) msg.obj;
                Log.i("获取的返回信息","+"+ReturnMessage+"+");
                if(ReturnMessage=="密码错误"||"密码错误".equals(ReturnMessage)){
                    Toast.makeText(LoginActivity.this, "密码错误",Toast.LENGTH_SHORT).show();

                }else if(ReturnMessage=="用户不存在"||"用户不存在".equals(ReturnMessage)){
                    Toast.makeText(LoginActivity.this, "登录失败，用户不存在",Toast.LENGTH_SHORT).show();
                }else{
                    User user= gson.fromJson(ReturnMessage,User.class);
                    Log.i("获取的返回信息","+"+user.toString()+"+");
                    SPUtil.getInstance(getApplicationContext()).putString("username",user.getUsername());
                    SPUtil.getInstance(getApplicationContext()).putString("phone",user.getPhone());
                    SPUtil.getInstance(getApplicationContext()).putString("photo",user.getPhotoUrl());
                    SPUtil.getInstance(getApplicationContext()).putString("useid",user.getUuid());
                    finish();
                    Intent intent;
                    intent = new Intent(LoginActivity.this, MainActivity.class);
                    startActivity(intent);
                }
                /***
                 * 在此处可以通过获取到的Msg值来判断
                 * 给出用户提示注册成功 与否，以及判断是否用户名已经存在
                 */

            }
        }
    }
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        mHandler = new Mhandler(this);
        setContentView(R.layout.activity_login);
        login=findViewById(R.id.login);
        user_edit=findViewById(R.id.usename);
        password_edit=findViewById(R.id.password);
        regs=findViewById(R.id.regs);
        regs.setOnClickListener(this);
        login.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        Intent intent;
        switch (v.getId()) {

            case R.id.regs:

                intent = new Intent(LoginActivity.this, RegisterActivity.class);
                startActivity(intent);
                break;
            case R.id.login:
                if("".equals(user_edit.getText().toString())||"".equals(password_edit.getText().toString())){
                    Toast.makeText(getApplicationContext(), "请输入正确的账号密码",Toast.LENGTH_SHORT).show();
                }else {
                    Log.e("ssss", user_edit.getText().toString()+password_edit.getText().toString());
                    postRequest(user_edit.getText().toString(),password_edit.getText().toString());
                }


                break;
            default:
                break;
        }
    }
    /**
     * post请求后台
     * @param username
     * @param password
     */
    private void postRequest(String username ,String password)  {
        //建立请求表单，添加上传服务器的参数
        RequestBody formBody = new FormBody.Builder()
                .add("phone",username)
                .add("password", password)
                .build();
        //发起请求
        final Request request = new Request.Builder()
                .url("http://120.26.177.58:8080/AndroidServer01/Login?")
                .post(formBody)
                .build();
        //新建一个线程，用于得到服务器响应的参数
        new Thread(new Runnable() {
            @Override
            public void run() {
                Response response = null;
                try {
                    //回调
                    response = client.newCall(request).execute();
                    if (response.isSuccessful()) {
                        //将服务器响应的参数response.body().string())发送到hanlder中，并更新ui
                        mHandler.obtainMessage(1, response.body().string()).sendToTarget();

                    } else {
                        throw new IOException("Unexpected code:" + response);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }).start();

    }
}

